<template>
	<view>
		<up-navbar
				title="蓝牙添加"
				@leftClick="leftClick"
				:autoBack="false"
				:placeholder="true"
		>
		</up-navbar>
		<view>
			<up-button text="搜索蓝牙" type="primary" @click="scanBleBT"></up-button>
		</view>
		<view>
			<up-list
				@scrolltolower="scrolltolower"
			>
				<up-list-item
					v-for="(item, index) in bluetoothDevicesList"
					:key="index"
					
				>
				<up-cell
					:title="item.name"
					:value="item.deviceId"
					@click="connectBleBT(item)"
				></up-cell>
				</up-list-item>
			</up-list>
		</view>

		<addEquipmentsTabbar></addEquipmentsTabbar>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import addEquipmentsTabbar from '@/components/tabbar/addEquipmentsTabbar/index.vue'
import { onMounted } from 'vue';
// import BluetoothManager from '@/utils/bluetooth.js'

let bluetoothDevicesList = reactive([{
	name: 'HH',
	deviceId: '00:23:07:36:71:87'
}])


const onLoad = () => {
  loadmore();
};

const scrolltolower = () => {
  loadmore();
};

const loadmore = () => {
  // for (let i = 0; i < 30; i++) {
  //   bluetoothDevicesList.value.push({
  //     url: urls[uni.$u.random(0, urls.length - 1)],
  //   });
  // }
};
// const manager = new BluetoothManager();

const leftClick = () => {
	uni.switchTab({
		url: '/pages/index/index',
		success: (e) => {
			console.log(e)
		},
		fail: (e) => {
			console.log(e)
		}
	})
}

// 搜索BLE蓝牙
const scanBleBT = () => {
	// bluetoothDevicesList = [{
	// 	name: 'HH',
	// 	deviceId: '00:23:07:36:71:87'
	// }]
	// 初始化蓝牙适配器
	uni.openBluetoothAdapter({
	  success: () => {
	    console.log('蓝牙适配器初始化成功');
	    // 请求蓝牙权限（仅移动端）
	   startDeviceSearch();
	  },
	  fail: (err) => {
	    console.error('蓝牙适配器初始化失败', err);
	  }
	});
	
	function startDeviceSearch() {
		uni.onBluetoothDeviceFound(function (res) {
		  const devices = res.devices;
		  devices.forEach((device) => {
		    console.log('发现新设备:', device);
				bluetoothDevicesList.push({
					name: device.name,
					deviceId: device.deviceId
				});
				
		    // 对每个新发现的设备进行处理，如展示在列表、连接等
		  });
		})
	  uni.startBluetoothDevicesDiscovery({
	    services: [], // 可选，指定需要搜索的服务UUID数组
	    allowDuplicatesKey: false, // 可选，是否允许重复上报同一设备
	    success: () => {
	      console.log('开始搜索蓝牙设备');
	    },
	    fail: (err) => {
	      console.error('启动蓝牙设备搜索失败', err);
	    }
	  });
		
		
	  // 在合适的时候停止搜索，例如搜索一定时间后或用户手动停止
	  setTimeout(stopDeviceSearch, 10000); // 假设搜索10秒后停止
	}
	
	function stopDeviceSearch() {
	  uni.stopBluetoothDevicesDiscovery({
	    success: () => {
	      console.log('停止搜索蓝牙设备');
	    },
	    fail: (err) => {
	      console.error('停止蓝牙设备搜索失败', err);
	    }
	  });
	}
}

// 搜索经典蓝牙
const scanBT = () => {
	if(typeof plus == "undefined") {
		console.log("非app平台，不支持plus")
	} else {
		if (plus.os.name === 'Android' || plus.os.name === 'ios') {
			console.log("当前平台支持蓝牙功能: " + plus.os.name);
			
			manager.searchDevices()
			.then((res) => {
					console.log("正在搜索设备...");
					// ...（等待一段时间或用户操作后）
					// return manager.stopSearching();
					setTimeout(() => {
						manager.stopSearching();
						res.forEach((value, key)=>{
							console.log(value, key)
							bluetoothDevicesList.push({
								name: value.name,
								deviceId: key
							});
						})
						return;
					}, 5000);
			})
			// .then(() => {
			// 		console.log("已停止搜索");
			// 		manager.discoveredDevices.forEach((value, key)=>{
			// 			console.log(value, key)
			// 		})
			// 		const targetDeviceAddress = "your_device_address";
			// 		const targetServiceUUID = "your_service_uuid";
			// 		return manager.connectToDevice(targetDeviceAddress, targetServiceUUID);
			// })
			// .then((socket) => {
			// 		const sendData = new Uint8Array([0x01, 0x02, 0x03, 0x04]);
			// 		return manager.sendData(socket, sendData);
			// })
			// .then(() => {
			// 		console.log("数据发送成功");
			// 		return manager.receiveData(socket);
			// })
			// .then((receivedData) => {
			// 		console.log("接收到数据:", receivedData);
			// })
			// .catch((error) => {
			// 		console.error(error.message);
			// 		// 处理错误情况
			// });
		} else {
			console.log("当前平台不支持蓝牙功能")
		}
	}
}

// 连接ble蓝牙
const connectBleBT = (v) => {
	console.log(v.deviceId)
	
	uni.navigateTo({
		url: `/pages/equipments/addEquipment/bluetooth/connectToBluetooth?
		name=${v.name}&deviceId=${v.deviceId}`
	})
	return;
	uni.createBLEConnection({
	  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
	  deviceId: v.deviceId,
	  success(res) {
	    console.log(res)
			setTimeout(() => {
				getBLEDeviceServices(v.deviceId);
			}, 1500)
	  }
	})
	uni.onBLEConnectionStateChange((res) => {
		const deviceId = res.deviceId;
		const connected = res.connected;

		if (connected) {
			console.log(`设备(${deviceId})连接状态变为：已连接`);
		} else {
			console.log(`设备(${deviceId})连接状态变为：已断开`);
			// 可在此处处理断开连接后的逻辑，如重连、通知用户等
		}
	});
	
	async function getBLEDeviceServices(deviceId) {
	  try {
	    const services = await uni.getBLEDeviceServices({
	      deviceId: deviceId,
	    });
	
	    console.log(`设备(${deviceId})提供的服务：`, services);
			
			// buff 转 str 
				function arrayBufferToString(buffer) {
			    let x = new Uint8Array(buffer);
			    // log(x)
			    let strHex = ""
			    let str = ""
			    for (let i = 0; i < x.length; i++) {
			      strHex = strHex + x[i].toString(16).padStart(2, "0")
			      str = str + String.fromCharCode(x[i])
			    }
					return strHex;
				}
				// str 转 buff
				function str2ab(str) {
					const buffer = new ArrayBuffer(str.length / 2);
					let x = new Uint8Array(buffer);
					for (let i = 0; i < x.length; i++) {
					    x[i] = parseInt(str.substr(2 * i, 2), 16)
					}
					return buffer;
				}
				
			
			uni.getBLEDeviceCharacteristics({
			  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			  deviceId,
			  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
			  serviceId: services.services[2].uuid,
			  success(res) {
			    console.log('device getBLEDeviceCharacteristics:', res.characteristics)
					
					// 向蓝牙设备发送一个0x00的16进制数据
					let msg = 'hello'
					    
					const buffer = new ArrayBuffer(msg.length)
					const dataView = new DataView(buffer)
					// dataView.setUint8(0, 0)
					
					for (var i = 0; i < msg.length; i++) {
						dataView.setUint8(i, msg.charAt(i).charCodeAt())
					}
					console.log(buffer)
					uni.writeBLECharacteristicValue({
					  // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					  deviceId,
					  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					  serviceId: services.services[2].uuid,
					  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					  characteristicId: res.characteristics[0].uuid,
					  // 这里的value是ArrayBuffer类型
					  value: buffer,
						writeType: 'writeNoResponse',
					  success(res) {
					    console.log('writeBLECharacteristicValue success', res.errMsg)
					  },
						fail(e){
							console.log("write fail: ", e)
						}
					})

			  }
			})
	    // 可在此处处理服务列表，如获取特征值、订阅通知等
	  } catch (error) {
	    console.error('获取蓝牙设备服务失败', error);
	  }
	}
}

// 连接经典蓝牙
const connectBT = (v) => {
	console.log(v.name, v.deviceId)
	const targetDeviceAddress = v.deviceId;
	const targetServiceUUID = "0000180D-0000-1000-8000-00805F9B34FB";
	manager.connectToDevice(targetDeviceAddress, targetServiceUUID)
	.then((socket) => {
		const sendData = new Uint8Array([0x01, 0x02, 0x03, 0x04]);
		console.log(socket)
		return manager.sendData(socket, sendData);
	})
	.then(() => {
		console.log("数据发送成功");
		return manager.receiveData(socket);
	})
}
</script>

<style>

</style>
